package com.example.springsecurity.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Aop 拦截器
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*
        * 首页所有人可以访问，功能页只有相应权限的人才可以访问
        *
        * */

        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认跳转至登录页面，需开启登陆页面
        http.formLogin().loginPage("/toLogin").passwordParameter("pass").usernameParameter("user").loginProcessingUrl("/login");
        //开启注销功能
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
    }

    //密码编码：passwordEncoder 对密码进行加密
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据应从数据库中读
        auth
                // enable in memory based authentication with a user named
                // "user" and "admin"
                .inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("user").password(new BCryptPasswordEncoder().encode("1234")).roles("vip1")
                    .and()
                    .withUser("admin").password(new BCryptPasswordEncoder().encode("1234")).roles("vip1","vip2","vip3")
                    .and()
                    .withUser("lihua").password(new BCryptPasswordEncoder().encode("1234")).roles("vip2","vip3");
    }
}
